<template>
  <div class="app-container">
    <div class="top-container">
      <div>
        <el-page-header :content="isEdit ? '编辑产品' : '新增产品'" @back="goBack" />
      </div>
      <div>
        <el-button
          class="filter-item"
          style="color:#4FA3F1"
          round
          size="small"
          :loading="confirmAddLoading"
          @click="submitForm(1)"
        >
          保存并新增
        </el-button>
        <el-button
          v-loading="loading"
          class="filter-item"
          round
          type="primary"
          size="small"
          :loading="confirmLoading"
          @click="submitForm()"
        >
          保存
        </el-button>
      </div>
    </div>
    <div class="createPost-container">
      <el-form v-if="!pageLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container">
        <div class="createPost-main-container">
          <label class="lab">基本信息</label>
           <el-form-item label="分类" prop="cate_id" :rules="[{ required: true, message: '名称不能为空', trigger: 'blur'}]">
            <el-select v-model="postForm.cate_id" placeholder="请选择分类" style="width:100%">
              <el-option v-for="item in cateList" :key="item.id" :label="_calcCategoryTitle(item)" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="名称"
            prop="title"
            :rules="[{ required: true, message: '名称不能为空', trigger: 'blur'}]"
          >
            <el-input v-model="postForm.title" :maxlength="150" />
          </el-form-item>
          <el-form-item prop="image_uri">
            <label>图片</label>
            <div class="upload-img-video">
              <img-upload multiple v-model="postForm.media" :maxNum="10"/>
            </div>
          </el-form-item>
          <el-form-item>
            <label>摘要</label>
            <el-input v-model="postForm.summary" type="textarea" :rows="3" :maxlength="300" />
          </el-form-item>
          <el-form-item prop="content">
            <label>內容</label>
            <rich-editor :key="tinyKey" :contents="postForm.content" @changeContent="contentChange" />
          </el-form-item>
          <label class="lab">
            <span style="margin-right: 35px;">产品参数</span>
            <el-button round icon="el-icon-plus" size="small" type="primary" @click="openAdditionDialog('add')">添加信息</el-button>
          </label>
          <el-table
            class="append-info"
            :data="postForm.additional"
            style="width: 100%"
          >
            <el-table-column prop="name" label="标题" width="300" />
            <el-table-column label="内容">
              <template slot-scope="{row}">
                <div class="addition-summary" v-html="row.summary" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center">
              <template slot-scope="{row, $index}">
                <div class="addition-option">
                  <el-tooltip class="operation" content="修改" placement="top">
                    <a @click="openAdditionDialog('edit', row, $index)">修改</a>
                  </el-tooltip>
                  <el-popconfirm
                    title="确定要删除此信息吗？"
                    @onConfirm="handleDelete($index)"
                  >
                    <el-tooltip slot="reference" class="operation" content="删除" placement="top">
                      <a style="margin-left: 10px;">删除</a>
                    </el-tooltip>
                  </el-popconfirm>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="createPost-right-container">
          <el-form-item>
            <label class="publish" style="color: #3E4850;font-size: 13px;">发布</label>
            <el-switch v-model="postForm.flag" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item>
            <label class="publish" style="color: #3E4850;font-size: 13px;">推荐</label>
            <el-switch v-model="postForm.recom" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item v-show="postForm.price_type == 2">
            <label class="publish" style="color: #3E4850;font-size: 13px;margin-right: 60px;">产品价格（￥）</label>
            <el-input-number v-model="postForm.price" controls-position="right"></el-input-number>
          </el-form-item>
          <el-form-item v-show="postForm.price_type == 2">
            <label class="publish" style="color: #3E4850;font-size: 13px;margin-right: 100px;">产品单位</label>
            <el-input style="width: 150px;" placeholder="请输入单位" v-model="postForm.price_unit"></el-input>
          </el-form-item>
          <el-form-item>
            <label style="display: inherit;">发布时间</label>
            <el-date-picker v-model="postForm.created_at" value-format="yyyy-MM-dd hh:mm:ss" type="datetime" format="yyyy-MM-dd hh:mm:ss" placeholder="选择日期" class="dateOption" />
          </el-form-item>
          <label class="lab font-bold">SEO配置</label>
          <div class="line-border mt-2" />
          <seo-form :key="tinyKey" :form-data.sync="postForm" />
        </div>
      </el-form>
      <loader :loading="pageLoading" />
    </div>

    <!-- 附加信息弹窗 -->
    <el-dialog
      :title="additionDialogTitle"
      :visible.sync="additionDialog"
      width="40%"
      custom-class="addition-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :append-to-body="true"
      top="10vh"
      @open="additionOpen"
    >
      <el-form
        label-width="100px"
        label-position="top"
        size="small"
      >
        <el-form-item label="标题">
          <el-input v-model="additionForm.name" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="additionForm.summary" :maxlength="150" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="additionDialog = false">
          取消
        </el-button>
        <el-button type="primary" @click="additionSubmit">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SeoForm from "@/components/SeoForm";
import imgUpload from '@/components/Upload/imgUpload.vue'
import RichEditor from '@/components/RichEditor'
import loader from '@/components/loader.vue'
import dayjs from 'dayjs'
import { calcCategoryTitle } from "@/utils"
import { getCateList } from "@/api/product-cate"

const defaultForm = {
  title: '',
  cate_id: '',
  slug: '',
  media: [],
  recom: 0,
  flag: 1,
  summary: '',
  content: '',
  tags: [],
  seo_title: '',
  seo_description: '',
  price: 0,
  price_unit: '',
  additional: [],
  created_at: ''
};

export default {
  name: "ProductDetail",
  components: { SeoForm, RichEditor, loader, imgUpload },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      pageLoading: false,
      loading: false,
      confirmLoading: false,
      confirmAddLoading: false,
      mediaIndex: 10000,
      rules: {
        cate_id: [{ required: true, message: '请选择分类', trigger: 'change'}]
      },
      value: 1,
      tempRoute: {},
      cateList: [],
      message: "",
      redirectUrl: "",
      imgUrl: require('@/assets/images/image.png'),
      tinyKey: new Date().getTime(),
      additionType: 'add',
      additionDialog: false,
      additionForm: {},
      additionIndex: null,
      additionEditorKey: null,
      page: null,
    };
  },
  computed: {
    additionDialogTitle()  {
      const text = {
        add: '添加',
        edit: '修改'
      }
      return text[this.additionType] + '附加信息'
    }
  },
  created() {
    if (this.isEdit) {
      if (this.$route.query.page) this.page = Number(this.$route.query.page)
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    } else {
      this.postForm.media = [];
    }
    this.getProductCate()
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    _calcCategoryTitle(item) {
      return calcCategoryTitle(item)
    },
    async fetchData(id) {
      this.pageLoading = true
      const response = await this.$request.get(`/product/${id}`);
      response.data.created_at = dayjs.unix(response.data.created_at).format('YYYY-MM-DD HH:mm:ss')
      this.postForm = this.$_.pick(response.data, Object.keys(defaultForm))
      this.postForm.id = response.data.id
      if (response.data.additional && response.data.additional.length > 0) {
        for (let i = 0; i < response.data.additional.length; i++) {
          this.postForm.additional[i].isSet = false
        }
      }
      this.tinyKey = new Date().getTime()
      this.pageLoading = false
    },
    async getProductCate() {
      const response = await getCateList();
      this.cateList = response.data
    },
    async submitForm(isCreate) {
      await this.$validate(this, "postForm");
      try {
        if (isCreate) {
          this.confirmAddLoading = true
        } else {
          this.confirmLoading = true
        }
        if (this.isEdit) {
          let form = Object.assign({}, this.postForm);
          await this.$request.put(
            `/product/${this.postForm.id}`,
            form
          )
        } else {
          await this.$request.post("/product", this.postForm)
        }
        if (isCreate) {
          this.confirmAddLoading = false
          this.message = this.isEdit ? "编辑成功！" : "添加成功！"
          this.redirectUrl = "/product/create"
          this.resetForm('postForm');
          this.tinyKey = new Date().getTime()
        } else {
          this.message = "保存成功！"
          this.redirectUrl = `/product/list?page=${this.page}`
        }
        this.$message({
          message: this.message,
          type: "success",
          showClose: true
        })
        this.$router.push(this.redirectUrl)
      } catch (error) {
        this.$message.error(error.response ? error.response.data.message : '网络异常！')
      } finally {
        this.confirmLoading = false
        this.confirmAddLoading = false
      }
    },
    contentChange(val) {
      this.postForm.content = val
    },
    goBack() {
      this.$router.push(`/product?page=${this.page}`)
    },
    openAdditionDialog(type, row, index) {
      this.additionType = type
      if (type === 'add') {
        this.additionForm = {
          name: '',
          summary: ''
        }
      } else {
        this.additionIndex = index
        this.additionForm = this.$_.pick(row, ['name', 'summary','id'])
      }
      this.additionDialog = true
    },
    handleDelete(index, type = 1) {
      if (type === 1) {
        this.postForm.additional.splice(index,1)
      } else {
        this.postForm.sku_att.splice(index,1)
        this.getSkus()
      }
    },
    async handleUpdate(row, index, flag, type = 1) {
      if (type == 1) {
        row.isSet = flag
        this.$set(this.postForm.additional, index, row)
      } else {
        await this.$validate(this, "postForm");
        row.isSet = flag
        this.$set(this.postForm.sku_att, index, row)
        if (flag === false) {
          this.getSkus()
        }
      }
    },
    // 表单重置
    resetForm(ref) {
      this.$refs[ref].resetFields()
      // 初始化默认数据
      this.postForm = this.$options.data().postForm
      this.postForm.media = [];
    },
    // 附加信息弹窗打开事件
    additionOpen() {
      this.additionEditorKey = new Date().getTime()
    },
    // 附加信息提交
    additionSubmit() {
      if (this.additionType === 'add') {
        this.postForm.additional.push(this.additionForm)
      } else {
        this.$set(this.postForm.additional, this.additionIndex, this.additionForm)
      }
      this.additionDialog = false
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;
  min-height: 200px;
  .form-container {
    display: flex;
    .el-form-item {
      margin-bottom: 20px;
      label {
        color: #7a92a5;
        font-size: 12px;
      }
    }
    .createPost-main-container {
      padding: 25px 45px 20px 40px;
      border-right: 2px solid #f0f4f7;
      width: 75%;
      .lab {
        font-size: 13px;
        line-height: 50px;
      }
      .append-info {
        margin-bottom: 20px;
        .option{
          text-align: right;
        }
      }
      .support {
        display: flex;
        flex-flow: wrap;
        justify-content: space-between;
        .el-form-item {
          width: 45%;
        }
      }
      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;
      }
    }
  }
  .createPost-right-container {
    flex: 1;
    padding: 25px 0px 0px 30px;
    .lab {
      font-size: 13px;
    }
    .publish {
      margin-right: 310px;
      font-weight: 700;
    }
    .dateOption {
      width: 380px;
    }
  }
}

.article-textarea {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}

.action-btn {
  cursor: pointer;
}
.addition-option {
  text-align: center;
  i {
    display: inline-block;
    margin: 0 5px;
  }
}
.addition-summary {
  height: 23px;
  overflow: hidden;
}
</style>

<style lang="scss">
.addition-dialog {
  border-radius: 5px;
  border-top: 3px solid #3B86FF;
  .el-dialog__header {
    border-bottom: 1px solid #efefef;
    margin-bottom: 10px;
  }
  .el-dialog__body {
    padding: 0 20px;
  }
}
</style>
